﻿// marine_organism_recognition_win.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include "pch.h"
#include <iostream>
#include <stdio.h>
#include <vector>
#include <opencv2/opencv.hpp>
//#include <opencv2/highgui/highgui.hpp>
//#include <opencv2/imgproc/imgproc.hpp>
#include "putText.h"
#include "ncnn_tools.h"
#include "darknet2ncnn.h"
#include "platform.h"
#include "net.h"
#if NCNN_VULKAN
#include "gpu.h"
#endif // NCNN_VULKAN

struct Object
{
	cv::Rect_<float> rect;
	int label;
	float prob;
};

static int detect_yolov3(const cv::Mat& bgr, std::vector<Object>& objects)
{
	//ncnn::Net yolov3;
	CustomizedNet yolov3;
	//register_darknet_layer(yolov3);


#if NCNN_VULKAN
	yolov3.opt.use_vulkan_compute = true;
#endif // NCNN_VULKAN

	// original pretrained model from https://github.com/eric612/MobileNet-YOLO
	// param : https://drive.google.com/open?id=1V9oKHP6G6XvXZqhZbzNKL6FI_clRWdC-
	// bin : https://drive.google.com/open?id=1DBcuFCr-856z3FRQznWL_S5h-Aj3RawA
	//yolov3.load_param("mobilenetv2_yolov3.param");
	//yolov3.load_model("mobilenetv2_yolov3.bin");
	yolov3.load_param("D:\\develop\\test_darknet_ncnn\\yolov3-voc.param");
	yolov3.load_model("D:\\develop\\test_darknet_ncnn\\yolov3-voc.bin");
	const int target_size = 416;
	//ncnn::Input *input = (ncnn::Input *)yolo.get_layer_from_name("data");
	int img_w = bgr.cols;
	int img_h = bgr.rows;

	ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_RGB, bgr.cols, bgr.rows, target_size, target_size);

	const float mean_vals[3] = { 127.5f, 127.5f, 127.5f };
	//const float norm_vals[3] = { 0.007843f, 0.007843f, 0.007843f };
	const float norm_vals[3] = { 1.0 / 256, 1.0 / 256, 1.0 / 256 };
	in.substract_mean_normalize(0, norm_vals);

	ncnn::Extractor ex = yolov3.create_extractor();
	ex.set_num_threads(4);

	ex.input("data", in);

	//ncnn::Mat out;

	//ex.extract("detection_out", out);

	ncnn::Mat out;
	for (size_t i = 0; i < 303; i++)
	{
		std::cout << i << "----" << yolov3.get_layer_from_index(i)->name << std::endl;
	}
	ncnn::Blob *out_blob = yolov3.get_last_layer_output_blob();
	std::cout << out_blob->name.c_str() << "----" << yolov3.get_last_layer_output_blob_index() << std::endl;
	int result = ex.extract(out_blob->name.c_str(), out);
	if (result != 0)
	{
		printf("ncnn error: %d\n", result);
		return result;
	}
	//     printf("%d %d %d\n", out.w, out.h, out.c);
	objects.clear();
	for (int i = 0; i < out.h; i++)
	{
		const float* values = out.row(i);

		Object object;
		object.label = values[0];
		object.prob = values[1];
		object.rect.x = values[2] * img_w;
		object.rect.y = values[3] * img_h;
		object.rect.width = values[4] * img_w - object.rect.x;
		object.rect.height = values[5] * img_h - object.rect.y;

		objects.push_back(object);
	}

	return 0;
}

static void draw_objects(const cv::Mat& bgr, const std::vector<Object>& objects)
{
	static const char* class_names[] = { "background",
		"海参", "海胆", "扇贝", "海星",
		"bottle", "bus", "car", "cat", "chair",
		"cow", "diningtable", "dog", "horse",
		"motorbike", "person", "pottedplant",
		"sheep", "sofa", "train", "tvmonitor" };

	cv::Mat image = bgr.clone();

	for (size_t i = 0; i < objects.size(); i++)
	{
		const Object& obj = objects[i];

		fprintf(stderr, "%d = %.5f at %.2f %.2f %.2f x %.2f\n", obj.label, obj.prob,
			obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height);
		cv::Scalar drawcolor;
		switch (obj.label)
		{
		case 1:
			rectangle(image, obj.rect, cv::Scalar(255, 0, 0));
			break;
		case 2:
			rectangle(image, obj.rect, cv::Scalar(0, 255, 0));
			break;
		default:
			rectangle(image, obj.rect, cv::Scalar(0, 0, 255));
			break;
		}
		//cv::rectangle(image, obj.rect, cv::Scalar(255, 0, 0));

		char text[256];
		sprintf(text, "%s %.1f%%", class_names[obj.label], obj.prob * 100);

		int baseLine = 0;
		cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);

		int x = obj.rect.x;
		int y = obj.rect.y - label_size.height - baseLine;
		if (y < 0)
			y = 0;
		if (x + label_size.width > image.cols)
			x = image.cols - label_size.width;

		cv::rectangle(image, cv::Rect(cv::Point(x, y),
			cv::Size(label_size.width, label_size.height + baseLine)),
			cv::Scalar(255, 255, 255), -1);
		//putTextZH(image, "力拔山兮气盖世", Point(30, 30), Scalar(0, 0, 0), 12, "华文行楷");
		putTextZH(image, text, cv::Point(x, y), Scalar(0, 0, 0), 18, "宋体");
		//cv::putText(image, text, cv::Point(x, y + label_size.height),
			//cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
	}

	cv::imshow("image", image);
	cv::waitKey(0);
}

int main(int argc, char** argv)
{
	if (argc != 2)
	{
		fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
		return -1;
	}

	const char* imagepath = argv[1];

	cv::Mat m = cv::imread(imagepath, 1);
	if (m.empty())
	{
		fprintf(stderr, "cv::imread %s failed\n", imagepath);
		return -1;
	}

#if NCNN_VULKAN
	ncnn::create_gpu_instance();
#endif // NCNN_VULKAN

	std::vector<Object> objects;
	detect_yolov3(m, objects);

#if NCNN_VULKAN
	ncnn::destroy_gpu_instance();
#endif // NCNN_VULKAN

	draw_objects(m, objects);

	return 0;
}


// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单

// 入门提示: 
//   1. 使用解决方案资源管理器窗口添加/管理文件
//   2. 使用团队资源管理器窗口连接到源代码管理
//   3. 使用输出窗口查看生成输出和其他消息
//   4. 使用错误列表窗口查看错误
//   5. 转到“项目”>“添加新项”以创建新的代码文件，或转到“项目”>“添加现有项”以将现有代码文件添加到项目
//   6. 将来，若要再次打开此项目，请转到“文件”>“打开”>“项目”并选择 .sln 文件
